package com.supermap.wzhy.module.fr.dao;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import java.util.List;

/**
 * 法人书库操作的DAO层
 * Created by W.Qiong on 16-12-23.
 */
public class FrDao {

    public SessionFactory sessionFactory ;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public List  query(String sql,Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;
        }
        try {
            return  query.list() ;
        }   catch (Exception e){
//            System.out.println("错误sql:"+sql);
            e.printStackTrace();
        }
        return  null ;
    }

    public int execute(String sql,Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;
        }
        try {
            return  query.executeUpdate();
        }   catch (Exception e){
            System.out.println("错误sql:"+sql);
            e.printStackTrace();
        }
        return 0;
    }

    public List  queryByPage(String sql,int start,int end, Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;
        }
        query.setFirstResult(start);              // 从0开始
        query.setMaxResults(end);    // 返回最大条数
        try {
            return  query.list() ;
        }   catch (Exception e){
            System.out.println("错误sql:"+sql);
        }
        return  null ;
    }

    public Integer  getIntegerUniq(String sql,Object... args){
        Query query  =  sessionFactory.openSession().createSQLQuery(sql) ;
        for(int i =0 ; i< args.length ;i++){
            query.setParameter(i,args[i]) ;
        }
        Integer re = 0;
        try {
             List list  = query.list() ;
             if(list.size()>0){
                 re = Integer.parseInt(list.get(0).toString()) ;
             }
        }   catch (Exception e){
            System.out.println("错误sql:"+sql);
            e.printStackTrace();
            re =0 ;
        }
        return  re ;
    }

}
